package it.eng.area118.mdocommon.ftp;

import it.eng.area118.mdocommon.android.log.BasicLogger;
import it.eng.area118.mdocommon.android.notification.AndroidNotificationManager;
import it.eng.area118.mdocommon.notification.SimpleAlertNotificationCallback;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;

public class FtptextFileTransferTask extends
		AsyncTask<FTPTextFileCompound, Integer, Boolean> {

	@Override
	protected Boolean doInBackground(FTPTextFileCompound... cmp) {
		try {
			SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy");
			FTPClient ftpClient = new FTPClient();
			InetAddress serverIp = InetAddress.getByAddress("10.118.12.3",
					new byte[] { 10, 118, 12, 3 });
			ftpClient.connect(serverIp);
			ftpClient.login(cmp[0].getUid(), cmp[0].getPwd());
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			BufferedInputStream buffIn = null;
			buffIn = new BufferedInputStream(new FileInputStream(
					cmp[0].getFilename()));
			ftpClient.enterLocalPassiveMode();
			ftpClient.storeFile(
					"ftplog_"
							+ "_"
							+ formatter
									.format(Calendar.getInstance().getTime())
							+ ".log", buffIn);
			buffIn.close();
			ftpClient.logout();
			ftpClient.disconnect();
			Handler handler = new Handler(Looper.getMainLooper());
			handler.post(new Runnable() {

				@Override
				public void run() {
					AndroidNotificationManager.getInstance().showSimpleAlert(
							"Trasferimento Ftp",
							"Trasferimento dei log FTP avvenuto con successo",
							new SimpleAlertNotificationCallback() {

								@Override
								public void onOk() {
									// TODO Auto-generated method stub

								}
							});
				}
			});
		} catch (Exception e) {
			BasicLogger.writeLog("FTP",
					"Error while executing storeTextFile()", e);
			
			return false;
		}
		return true;
	}
}
